package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*用为事务，所以在service中添加intefaceClass*/
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleDao roleDao;

    //查询所有权限
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    //角色数据添加
    public void add(Role role,Integer[] permissionIds) {
        roleDao.add(role);
        //调用建多表工具类
        this.addAssociationUtils(role.getId(),permissionIds);
    }

    //通用分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //limit
        PageHelper.startPage(currentPage,pageSize);
        //装载有页面数据，其实可以直接返回Page,但是公司一般自己定义页面数据，也就是PageResult,page中的数据提取出来再封装在pageResult中
        Page<Role> page = roleDao.findRoleByCondition(queryString);
        long total = page.getTotal();
        List<Role> rows = page.getResult();
        PageResult pageResult = new PageResult(total, rows);
        return pageResult;
    }

    //回显role基本信息
    public Role findRoleById(Integer roleId) {
        Role role = roleDao.findRoleById(roleId);
        return role;
    }

    //编辑角色信息
    public void updateEdit(Role role,Integer[] permissionIds) {
        //编辑角色信息
        roleDao.updateEdit(role);
        //根据id删除角色与权限对应的多表
        roleDao.deleteRoleAndPermission(role.getId());
        //调用建多表工具类
        this.addAssociationUtils(role.getId(),permissionIds);
    }

    //回显勾选角色对应的权限
    public List<Integer> findPermissionIdsByRoleId(Integer roleId) {
        return roleDao.findPermissionIdsByRoleId(roleId);
    }

    //根据id删除角色
    public void delete(Integer id) throws RuntimeException {
        //根据id删除角色与用户对应的多表
       roleDao.deleteRoleAndUser(id);
        //根据id删除角色与权限对应的多表
       roleDao.deleteRoleAndPermission(id);
        //根据id删除角色与菜单对应的多表
       roleDao.deleteRoleAndMenu(id);
        //根据id删除角色
       roleDao.delete(id);
    }

    //添加角色与权限的多表关系
    public void addAssociationUtils(Integer roleId,Integer[] permissionIds) {
        Map map = new HashMap();
        for (Integer permissionId : permissionIds) {
            map.put("roleId", roleId);
            map.put("permissionId", permissionId);
            roleDao.addAssociation(map);
        }
    }
}
